package prompts

import (
	"bytes"
	"text/template"
)

// Template represents a prompt template
type Template struct {
	Name     string
	Content  string
	template *template.Template
}

// TemplateData contains data for template rendering
type TemplateData map[string]interface{}

// NewTemplate creates a new prompt template
func NewTemplate(name, content string) (*Template, error) {
	tmpl, err := template.New(name).Parse(content)
	if err != nil {
		return nil, err
	}

	return &Template{
		Name:     name,
		Content:  content,
		template: tmpl,
	}, nil
}

// Render renders the template with given data
func (t *Template) Render(data TemplateData) (string, error) {
	var buf bytes.Buffer
	if err := t.template.Execute(&buf, data); err != nil {
		return "", err
	}
	return buf.String(), nil
}

// TemplateManager manages multiple templates
type TemplateManager struct {
	templates map[string]*Template
}

// NewTemplateManager creates a new template manager
func NewTemplateManager() *TemplateManager {
	return &TemplateManager{
		templates: make(map[string]*Template),
	}
}

// AddTemplate adds a template to the manager
func (m *TemplateManager) AddTemplate(name, content string) error {
	tmpl, err := NewTemplate(name, content)
	if err != nil {
		return err
	}
	m.templates[name] = tmpl
	return nil
}

// GetTemplate retrieves a template by name
func (m *TemplateManager) GetTemplate(name string) (*Template, bool) {
	tmpl, ok := m.templates[name]
	return tmpl, ok
}
